<?php

namespace cms\modules\v1\models\images;

use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\image\Image;
use yii\base\Exception;
use Yii;
/**
 * This is the model class for table "project_info".
 *
 * @property int $id
 * @property string $name
 */
class Images extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%images}}';
    }

    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            #登录
            [['position_id'], 'required','message' => '{attribute}不能为空','on' => 'addEdit'],
        ];
    }

    /**
     * 设置属性名称
     * @return array
     */
    public function attributeLabels() {
        return [
            'position_id' => '位置',
            'list_order' => '排序',
            'status' => '状态',
            'image' => '状态',
            'url' => '跳转路径',
            'jump_type' => '跳转类型',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios() {
        $newScenarios =  [
            'addEdit' => [
                'position_id',
                'list_order',
                'status',
//                'url',
//                'jump_type'
            ],
        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @param array $search
     * @return array
     */
    public function getListData($page = 1, $size = 20, $search = []) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch($search);//自定义搜索条件
            $query = new Image();
            $count = 0;
            //得到文章的总数
            if(isset($searchWhere['andWhere'])){
                $count = $query::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            }

            $data = static::setPageinationAPI($count, $page, $size);

            $returnData = [
                'total' => (int ) $count,
                'page' => (int) $page,
                'totalPage' => (int) $data['totalPage'],
                "data" => null
            ];

            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id ASC';

            if(isset($searchWhere['andWhere'])){
                $query = $query::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            }

            $returnData['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $returnData);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     *  自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @param array $search
     * @return array
     */
    public function getSearch ($search = []) {
        $where = [];
        $andWhere = [];
        $search = json_decode($search,true);
        if(!empty($search)){
            $positionId = isset($search['position_id']) ? $search['position_id'] : '';
            $status = isset($search['status']) ? $search['status'] : '';
            if($status) {
                $where['status'] = (int) $status;
            }

            if($positionId) {
                $where['position_id'] = (int) $positionId;
            }
        }
        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with(['type'])
            ->asArray()->all();

        $result = [];
        foreach ($list as $k => $v) {
            $result[] = [
                'id' => (int) $v['id'],
                'position_name' => $v['type'] ? $v['type']['position_name'] : '',
                'aspect_radio' => $v['type'] ? $v['type']['aspect_ratio'] : '',
//                'image' => $this->imageHost . $v['image'],
                'image' => \common\models\Common::getImages($v['image']),
                'status' => $v['status'],
                'list_order' => $v['list_order'],
                'url' => $v['url'],
                'jump_type' => $v['jump_type'],
            ];
        }
        return $result;
    }


    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $post = Yii::$app->request->post();
            $id = isset($post['id']) ? $post['id'] : 0;
            $data = [];

            if (!empty($id)) {
                //更新操作
                $data = array_merge($data, $this->getSaveData($this->scenario, $post));
                $info = static::getOneByWhere(['id' => $id],['image']);
                $data['update_time'] = date('Y-m-d H:i:s');

                if (!empty($post['image'])) {
                    $data['image'] =  $post['image'];
                }
                $res = static::updateDataWithLog($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('更新失败');
                }

            } else {
                //添加操作
                $data = array_merge($data, $this->getSaveData($this->scenario, $post));
                $data['update_time'] = $data['create_time'] =  date('Y-m-d H:i:s');
                if (empty($post['image'])) {
                    throw new Exception('图片信息不能为空');
                }
                //如果是上传
                $data['image'] = $post['image'];

                $res = static::insertDataWithLog($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }

            }
            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getInfo($id = 0) {
        try {
            $info = static::getOneInfoById($id);

            if (empty($info)) {
                throw new Exception('未知图片信息');
            }

            $info['image'] = $this->imageHost . $info['image'];
            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

}
